import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getCartGoodsCount } from '@/api/cart'
import router from '@/router'
import Vue from 'vue'

const state = {
  token: getToken(),
  id: '',
  name: '',
  userInfo: {},
  isRefresh: false,
  cartCount:'',
  active: 0,
  errorImg: Vue.prototype.$errorImg
}

const mutations = {
  SET_ERROR_IMG:(state, errorImg) => {
    state.errorImg = errorImg
  },
  SET_CART_COUNT:(state, count) => {
    state.cartCount = count
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, info) => {
    state.userInfo = info
    state.id = info.id
    state.name = info.nickname
  },
  setIsRefresh: (state, isRefresh) => {
    state.isRefresh = isRefresh
  },
  setActive: (state, active) => {
    state.active = active
  }
}

const actions = {

  getCartGoodCount({commit}) {
    return new Promise((resolve, reject) => {
      getCartGoodsCount().then(res => {
        // debugger
        const { count } = res.map
        commit('SET_CART_COUNT',count)
        resolve()
      })
    })
  },

  // 登录
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile, password })
        .then(res => {
          console.log(res)
          if(res.code!== 200){
            
            reject(res.msg)
          }
          const { token } = res.map
          commit('SET_TOKEN', token)
          // sessionStorage.setItem('token', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 登出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          removeToken()

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取基本用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(res => {
          const data = res.map
          if (!data) {
            reject(new Error('获取基本信息失败，请重新登录'))
          }
          if(data.info.status == 1){
            commit('SET_TOKEN', '')
            removeToken()
            router.push({name:'Login'})
          }
          commit('SET_USER_INFO', data.info)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
